package cn.unknowpupil.init.utils.security;


import cn.unknowpupil.init.domain.dto.LoginUser;
import cn.unknowpupil.init.exceptions.HealthException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * Created at 2020/10/19 by w10g <br>
 * Initialize SecurityUtils ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
public class SecurityUtils {
    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            Authentication principal = getAuthentication();
            if(Objects.isNull(principal)){
                return null;
            }else {
                return (LoginUser)principal.getPrincipal();
            }
        } catch (Exception e) {
            throw new HealthException(e.getMessage());
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 是否为管理员
     *
     * @param pid 顶级ID
     * @return 结果
     */
    public static boolean isAdmin(Long pid)
    {
        return pid != null && 0L == pid;
    }
}
